/*******商品路由器模块product.js*******/
const {
	REFUSED
} = require('dns')
const express = require('express')
const pool = require('../pool.js')
const router = express.Router()
module.exports = router

//1.查询MS_food表中所有菜品的fid fname
//GET /showfood 没有参数
//返回值：所有商品的fid fname
//测试地址：http://127.0.0.1:8000/v2/f/showfood
router.get('/showfood', (req, res) => {
	let sql = 'select fid,fname from MS_food'
	pool.query(sql, (err, result) => {
		if (err) throw err
		res.send(result)
	})
})


//2.声明菜品路由，检查执行数量的数据
//GET /list
//请求参数： pageSize=n
//返回值：指定数量的商品的fid fname
//测试地址：http://127.0.0.1:8080/v2/f/list?pageSize=
//limit后两个值，表示从哪个索引开始，每页的数量
//limit后一个值，表示从第一条数据开始，查询n条数据
router.get('/list', (req, res) => {
	let sql = 'select fid,fname from MS_food limit ?'
	let ps = req.query.pageSize
	ps = ps ? parseInt(ps) : 5
	pool.query(sql, [ps], (err, result) => {
		if (err)
			throw err
		res.send(result)
	})
})


//3.声明菜品路由，添加菜谱相关数据
//POST /add
////测试地址：http://127.0.0.1:8080/v2/f/add
router.post('/add', (req, res) => {

	if (!req.body.fname) {
		// res.send({code:201,msg:'菜名不为空！'})
		res.send('菜名不为空！')
		return
	}
	if (!req.body.fprop) {
		// res.send({code:201,msg:'菜谱食材不为空！'})
		res.send('菜谱食材不为空！')
		return
	}
	if (!req.body.fstep) {
		// res.send({code:201,msg:'菜谱步骤不为空！'})
		res.send('菜谱步骤不为空！')
		return
	}
	req.body.ftypeid = parseInt(req.body.ftypeid)
	pool.query('insert into MS_food set ?', [req.body], (err, result) => {
		if (err)
			throw err
		// res.send({code:200,msg:'菜谱新增成功'})
		res.send('菜谱新增成功')
	})
})

router.get('/today', (req, res) => {
	let sql = 'select * from ms_food order by rand() limit 8'
	pool.query(sql, (err, result) => {
		if (err)
			throw err
		res.send(result)
	})
})

router.get('/new', (req, res) => {
	let sql = 'select * from ms_food order by fid desc limit 8'
	pool.query(sql, (err, result) => {
		if (err)
			throw err
		res.send(result)
	})
})

// "`http://127.0.0.1:8080/v2/f/title_type?ftypeid=${ftypeid.value}&page=${page.value}`"
router.get('/title_type', (req, res) => {
	let limit_1 = (req.query.page - 1) * 8
	let sql = `select * from ms_food where ftypeid=? limit ?,8`
	// console.log(req.query.ftypeid, typeof req.query.ftypeid);
	pool.query(sql, [req.query.ftypeid, limit_1], (err, result) => {
		if (err)
			throw err
		res.send(result)
		// console.log(sql);
	})
})

router.get('/page', (req, res) => {
	let sql = 'select count(*) as num from ms_food where ftypeid=?'
	pool.query(sql,[req.query.ftypeid], (err, result) => { 
		if (err)
			throw err
		res.send(result)
	})
})

// select * from ms_food order by fid desc limit 8
// select * from ms_food order by rand() limit 8
// select * from ms_food where ftypeid=1
// select count(*) from ms_food
